package com.example.qcweb;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.modal.WorkingProcedure;
import com.example.qc.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Gongyi_Activity extends Activity {
    /*
	 * public static String[] array = { "text1,", "text2", "text3", "text4",
	 * "text5,", "text6", "text7", "text8" };
	 */
    // public static String[] array=new String[]{};
    // public List<WorkProcedure> array=DBGlobal.QCCardWorkProduce(this);

    /**
     * Called when the activity is first created.
     */
    public static String producestrString;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //无标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gongyi_activity);

    }

    public static class TitlesFragment extends ListFragment {

        boolean mDualPane;
        int mCurCheckPosition = 0;
        View oldView;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            System.out.println("Fragment-->onCreate");
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            System.out.println("Fragment-->onCreateView");
            return super.onCreateView(inflater, container, savedInstanceState);
        }

        @Override
        public void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            System.out.println("Fragment-->onPause");
        }

        @Override
        public void onStop() {
            // TODO Auto-generated method stub
            super.onStop();

            System.out.println("Fragment-->onStop");
        }

        @Override
        public void onAttach(Activity activity) {
            // TODO Auto-generated method stub
            super.onAttach(activity);
            System.out.println("Fragment-->onAttach");
        }

        @Override
        public void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            System.out.println("Fragment-->onStart");
        }

        @Override
        public void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            System.out.println("Fragment-->onResume");
        }

        @Override
        public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            System.out.println("Fragment-->onDestroy");
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onActivityCreated(savedInstanceState);
            System.out.println("Fragment-->onActivityCreted");
            Map<String, List<WorkingProcedure>> workmap = DBGlobal
                    .QCCardWorkProduce(this.getActivity());

			/*
			 * Object[] strarray=new Object[workmap.size()]; Set
			 * keySet=workmap.keySet(); strarray= keySet.toArray();
			 */
            Object[] obj = workmap.keySet().toArray();
            String[] strarray = new String[workmap.size()];
            for (int i = 0; i < strarray.length; i++) {
                strarray[i] = "工序" + String.valueOf(obj[i]);
            }

            setListAdapter(new ArrayAdapter<Object>(getActivity(),
                    android.R.layout.simple_list_item_1, strarray));

            View detailsFrame = getActivity().findViewById(R.id.details);

            mDualPane = detailsFrame != null
                    && detailsFrame.getVisibility() == View.VISIBLE;

            if (savedInstanceState != null) {
                mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
            }

            if (mDualPane) {
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

                showDetails(mCurCheckPosition);
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            // TODO Auto-generated method stub
            super.onSaveInstanceState(outState);

            outState.putInt("curChoice", mCurCheckPosition);
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            // TODO Auto-generated method stub
            super.onListItemClick(l, v, position, id);
            v.setBackgroundColor(Color.rgb(176, 196, 222));
            if (oldView != null && oldView != v) {
                oldView.setBackgroundColor(Color.rgb(77, 73, 72));

            }
            oldView = v;
            showDetails(position);
        }

        void showDetails(int index) {
            mCurCheckPosition = index;
            if (mDualPane) {
                getListView().setItemChecked(index, true);
                Fragment currentFragment = getFragmentManager().findFragmentById(R.id.details);
				
				/*DetailsFragment details = (DetailsFragment) getFragmentManager()
						.findFragmentById(R.id.details);*/


                //if (details == null || details.getShownIndex() != index) {
                DetailsFragment details = DetailsFragment.newInstance(mCurCheckPosition);


                FragmentTransaction ft = getFragmentManager()
                        .beginTransaction();
                ft.replace(R.id.details, details);

                //	ft.addToBackStack(null);
                ft.commit();// 鎻愪氦
                //}
            } //else {
				/*
				 * new AlertDialog.Builder(getActivity()).setTitle(
				 * android.R.string.dialog_alert_title).setMessage(
				 * array[index]).setPositiveButton(android.R.string.ok,
				 * null).show();
				 */
            //}
        }
    }

    /**
     * 浣滀负鐣岄潰鐨勪竴閮ㄥ垎锛屼负fragment 鎻愪緵涓�釜layout
     *
     * @author terry
     */
    public static class DetailsFragment extends Fragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
        }

        public static DetailsFragment newInstance(int index) {
            DetailsFragment details = new DetailsFragment();
            Bundle args = new Bundle();
            args.putInt("index", index);
            details.setArguments(args);
            return details;
        }

        public int getShownIndex() {
            return getArguments().getInt("index", 0);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            if (container == null)
                return null;

            // ScrollView scroller = new ScrollView(getActivity());
			/*
			 * TextView text = new TextView(getActivity());
			 * 
			 * int padding = (int) TypedValue.applyDimension(
			 * TypedValue.COMPLEX_UNIT_DIP, 4, getActivity()
			 * .getResources().getDisplayMetrics()); text.setPadding(padding,
			 * padding, padding, padding); scroller.addView(text); //
			 * List<WorkProcedure>
			 * array=DBGlobal.QCCardWorkProduce(this.getActivity());
			 * Map<String,List<WorkProcedure>>
			 * workmap=DBGlobal.QCCardWorkProduce(this.getActivity());
			 * 
			 * //text.setText(array.get(getShownIndex()).getContent()); String
			 * position=String.valueOf(getShownIndex()+1); String string=null;
			 * //获取长度 int
			 * len=workmap.get(String.valueOf(getShownIndex()+1)).size();
			 * //获取工序对应的工步 for (int i = 0; i <len; i++) {
			 * string+=workmap.get(String
			 * .valueOf(getShownIndex()+1)).get(i).getContent(); }
			 * text.setText(string);
			 */

            TextView cardName = (TextView) getActivity().findViewById(R.id.cardname);

            String position = String.valueOf(getShownIndex() + 1);
            // 获取长度
            Map<String, List<WorkingProcedure>> workmap = DBGlobal.QCCardWorkProduce(this.getActivity());
            int len = workmap.get(position).size();
            List<WorkingProcedure> list = workmap.get(position);
            producestrString = String.valueOf("工序" + position + ":" + list.get(0).getContent());
            //////////////produceName.setText(producestrString);
            cardName.setText(MyGlobal.KeycardCode + "质控卡");
            List<WorkingProcedure> subList = list.subList(1, list.size());
            ListView lvListView = new ListView(getActivity());
            stepadapter adapter = new stepadapter(getActivity(), subList);
            lvListView.setAdapter(adapter);

            // scroller.addView(lvListView);
            return lvListView;
        }

        public class stepadapter extends BaseAdapter {
            List<WorkingProcedure> worklist = new ArrayList<WorkingProcedure>();
            // int lenth;
            private LayoutInflater inflater;
            WorkingProcedure wp;
            int pp;

            // String pString;
            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return worklist.size();
            }

            public stepadapter(Context context, List<WorkingProcedure> arglist) {
                super();
                inflater = LayoutInflater.from(context);
                worklist = arglist;

                // TODO Auto-generated constructor stub
            }

            @Override
            public Object getItem(int arg0) {
                // TODO Auto-generated method stub
                return worklist.get(arg0);
            }

            @Override
            public long getItemId(int arg0) {
                // TODO Auto-generated method stub
                return arg0;
            }

            public class ViewHolder {
                public TextView gongbuContent;
                public ImageButton partItemButton;
                public ImageButton examButton;
                public ImageButton multMediaButton;
                public ImageView imageView;
                public TextView gongbuName;

            }

            @Override
            public View getView(int arg0, View arg1, ViewGroup arg2) {
                // TODO Auto-generated method stub
                ViewHolder viewHolder;
                if (arg1 == null) {
                    arg1 = inflater.inflate(R.layout.activity_listcell, null);
                    viewHolder = new ViewHolder();
                    viewHolder.gongbuContent = (TextView) arg1.findViewById(R.id.tvgongbu);
                    //viewHolder.button = (Button) arg1.findViewById(R.id.button1);
                    viewHolder.partItemButton = (ImageButton) arg1.findViewById(R.id.imgbtnPart);
                    viewHolder.examButton = (ImageButton) arg1.findViewById(R.id.imgbtnExam);
                    viewHolder.multMediaButton = (ImageButton) arg1.findViewById(R.id.imgbtnMultMedia);
                    viewHolder.gongbuName = (TextView) arg1.findViewById(R.id.tvgongxu);
                    // viewHolder.imageView=(ImageView)arg1.findViewById(R.id.imageView1);

                    arg1.setTag(viewHolder);

                } else {
                    viewHolder = (ViewHolder) arg1.getTag();
                }
                wp = worklist.get(arg0);
                viewHolder.gongbuContent.setText(worklist.get(arg0).getContent());
                viewHolder.gongbuName.setText("工步" + String.valueOf(arg0 + 1));
                viewHolder.partItemButton.setOnClickListener(new lvButtonListener(wp));
                viewHolder.examButton.setOnClickListener(new lvButtonListener(wp));
                viewHolder.multMediaButton.setOnClickListener(new lvButtonListener(wp));
                viewHolder.gongbuContent.setOnClickListener(new lvButtonListener(wp));
				/*viewHolder.button.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {
								TextView text = new TextView(getActivity());

								int padding = (int) TypedValue.applyDimension(
										TypedValue.COMPLEX_UNIT_DIP, 4,
										getActivity().getResources()
												.getDisplayMetrics());
								text.setPadding(padding, padding, padding,
										padding);
								text.setText("syl");

							}
						});*/

                return arg1;
            }

            class lvButtonListener implements OnClickListener {
                private WorkingProcedure workproduce;

                public lvButtonListener(WorkingProcedure workp) {
                    super();
                    this.workproduce = workp;
                }

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    switch (arg0.getId()) {
                        case R.id.imgbtnPart:
                            //Toast.makeText(getActivity(), "零件", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), PartItemActivity.class);
                            intent.putExtra("key", workproduce);
                            startActivity(intent);
                            break;
                        case R.id.imgbtnExam:
                            // Toast.makeText(getActivity(), "实测", Toast.LENGTH_LONG).show();
                            Intent intent1 = new Intent();
                            intent1.setClass(getActivity(), ExamItemActivity.class);
                            intent1.putExtra("key", workproduce);
                            startActivity(intent1);
                            break;
                        case R.id.imgbtnMultMedia:
                            //Toast.makeText(getActivity(), "多媒体", Toast.LENGTH_LONG).show();
                            Intent intent2 = new Intent();
                            intent2.setClass(getActivity(), MultMediaActivity.class);
                            intent2.putExtra("key", workproduce);
                            startActivity(intent2);
                            break;

                        case R.id.tvgongbu:
                            //Toast.makeText(getActivity(), "工步内容", Toast.LENGTH_LONG).show();
                            //Fragment_StepContent fragment_StepContent=new Fragment_StepContent();
                            Fragment_StepContent frgstep = Fragment_StepContent.newInstance(workproduce);
		            	/*Bundle bundle=new Bundle();
		            	bundle.putInt("key", pp);
		                fragment_StepContent.setArguments(bundle);*/
                            FragmentTransaction fTransaction = getFragmentManager().beginTransaction();
                            fTransaction.replace(R.id.details, frgstep);
                            fTransaction.addToBackStack(null);
                            fTransaction.commit();


                            break;

                    }
                }

            }

        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            // TODO Auto-generated method stub
            super.onCreateOptionsMenu(menu, inflater);
            menu.add("Menu 1a")
                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            menu.add("Menu 1b")
                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // TODO Auto-generated method stub
            Toast.makeText(
                    getActivity(),
                    "index is" + getShownIndex() + " && menu text is "
                            + item.getTitle(), 1000).show();
            return super.onOptionsItemSelected(item);
        }
    }

}
